package org.rocky.provider.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 发送消息到直连交换机
 * @author Rocky
 * @date 2020/2/17 17:33
 */
@RestController
@RequestMapping("/provider/direct")
public class SendDirectController {
    Logger log =  LoggerFactory.getLogger(SendDirectController.class);
    private RabbitTemplate rabbitTemplate;


    @Autowired
    public SendDirectController( RabbitTemplate rabbitTemplate){
        this.rabbitTemplate= rabbitTemplate;
    }

    /**
     * 发送到正确的队列
     * @param info 消息
     * @return 页面
     */
    @RequestMapping("/sendRightHost")
    public String sendRightHost(String info){
        String msg = "direct msg " + info;
        Message message = new Message(msg.getBytes(),new MessageProperties());
        rabbitTemplate.send("DIRECT_EXCHANGE","rocky.exchange",message);
        return "success";
    }

    /**
     * 发送消息给错误的host
     * 已经配置了异步消息确认机制的话异常不影响服务
     * @param info 消息
     * @return 页面
     */
    @RequestMapping("/sendErrorHost")
    public String sendErrorHost(String info){
        String status = "fail";
        try{
            String msg = "direct msg " + info;
            Message message = new Message(msg.getBytes(),new MessageProperties());
            rabbitTemplate.convertAndSend("AA_EXCHANGE","rocky.exchange",message);
        }catch (Exception e){
            status = "success";
            log.warn("error host");
        }
        return status;
    }


    /**
     * 发送消息给错误的键
     * 已经配置了异步消息确认机制的话异常不影响服务
     * 目前已配置服务备份交换机转发
     * @param info 消息
     * @return 页面
     */
    @RequestMapping("/sendErrorKey")
    public String sendErrorKey(String info){
        String status = "fail";
        try{
            String msg = "direct msg " + info;
            Message message = new Message(msg.getBytes(),new MessageProperties());
            rabbitTemplate.send("DIRECT_EXCHANGE","rocky.aa",message);
        }catch (Exception e){
            status = "success";
            log.warn("error key");

        }
        return status;
    }

}
